package com.project.common.util;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.zip.DataFormatException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.project.common.Constants;

/**
 * 提供日期/時間轉換的公用程式方法<br/>
 * 
 * @author Chiu Han-sung, 2007/01/27<br/>
 * 
 */
public class DateUtil {
    static Log                 log              = LogFactory.getLog(DateUtil.class);
    // 各年度農曆一月一日之西元年/月/日對照表
    public static final String dateYanDanDate[] = { "1901/02/19", "1902/02/08", "1903/01/29",
            "1904/02/16", "1905/02/04", "1906/01/25", "1907/02/13", "1908/02/02", "1909/01/22",
            "1910/02/10", "1911/01/30", "1912/02/18", "1913/02/06", "1914/01/26", "1915/02/14",
            "1916/02/03", "1917/01/23", "1918/02/11", "1919/02/01", "1920/02/20", "1921/02/08",
            "1922/01/28", "1923/02/16", "1924/02/05", "1925/01/24", "1926/02/13", "1927/02/02",
            "1928/01/23", "1929/02/10", "1930/01/30", "1931/02/17", "1932/02/06", "1933/01/26",
            "1934/02/14", "1935/02/04", "1936/01/24", "1937/02/11", "1938/01/31", "1939/02/19",
            "1940/02/08", "1941/01/27", "1942/02/15", "1943/02/05", "1944/01/25", "1945/02/13",
            "1946/02/02", "1947/01/22", "1948/02/10", "1949/01/29", "1950/02/17", "1951/02/06",
            "1952/01/27", "1953/02/14", "1954/02/03", "1955/01/24", "1956/02/12", "1957/01/31",
            "1958/02/18", "1959/02/08", "1960/01/28", "1961/02/15", "1962/02/05", "1963/01/25",
            "1964/02/13", "1965/02/02", "1966/01/21", "1967/02/09", "1968/01/30", "1969/02/17",
            "1970/02/06", "1971/01/27", "1972/02/15", "1973/02/03", "1974/01/23", "1975/02/11",
            "1976/01/31", "1977/02/18", "1978/02/07", "1979/01/28", "1980/02/16", "1981/02/05",
            "1982/01/25", "1983/02/13", "1984/02/02", "1985/02/20", "1986/02/09", "1987/01/29",
            "1988/02/17", "1989/02/06", "1990/01/27", "1991/02/15", "1992/02/04", "1993/01/23",
            "1994/02/10", "1995/01/31", "1996/02/19", "1997/02/07", "1998/01/28", "1999/02/16",
            "2000/02/05", "2001/01/24", "2002/02/12", "2003/02/01", "2004/01/22", "2005/02/09",
            "2006/01/29", "2007/02/18", "2008/02/07", "2009/01/26", "2010/02/14", "2011/02/03",
            "2012/01/23", "2013/02/10", "2014/01/31", "2015/02/19", "2016/02/08", "2017/01/28",
            "2018/02/16", "2019/02/05", "2020/01/25", "2021/02/12", "2022/02/01", "2023/01/22",
            "2024/02/10", "2025/01/29", "2026/02/17", "2027/02/06", "2028/01/26", "2029/02/13",
            "2030/02/03", "2031/01/23", "2032/02/11", "2033/01/31", "2034/02/19", "2035/02/08",
            "2036/01/28", "2037/02/15", "2038/02/04", "2039/01/24", "2040/02/12", "2041/02/01",
            "2041/02/01", "2043/02/10", "2044/01/30", "2045/02/17", "2046/02/06", "2047/01/26",
            "2048/02/14", "2049/02/02", "2050/01/23", "2051/02/11", "2052/02/01", "2053/02/19",
            "2054/02/08", "2055/01/28", "2056/02/15", "2057/02/04", "2058/01/24", "2059/02/12",
            "2060/02/02", "2061/01/21", "2062/02/09", "2063/01/29", "2064/02/17", "2065/02/05",
            "2066/01/26", "2067/02/14", "2068/02/03", "2069/01/23", "2070/02/11", "2071/01/31",
            "2072/02/19", "2073/02/07", "2074/01/27", "2075/02/15", "2076/02/05", "2077/01/24",
            "2078/02/12", "2079/02/02", "2080/01/22", "2081/02/09", "2082/01/29", "2083/02/17",
            "2084/02/06", "2085/01/26", "2086/02/14", "2087/02/03", "2088/01/24", "2089/02/10",
            "2090/01/30", "2091/02/18", "2091/02/18", "2093/01/27", "2094/02/15", "2095/02/05",
            "2096/01/25", "2097/02/12", "2098/02/01", "2099/01/21", "2100/02/09" };
    // 西元年對照表
    public static final String dateYear[]       = { "1901", "1902", "1903", "1904", "1905", "1906",
            "1907", "1908", "1909", "1910", "1911", "1912", "1913", "1914", "1915", "1916", "1917",
            "1918", "1919", "1920", "1921", "1922", "1923", "1924", "1925", "1926", "1927", "1928",
            "1929", "1930", "1931", "1932", "1933", "1934", "1935", "1936", "1937", "1938", "1939",
            "1940", "1941", "1942", "1943", "1944", "1945", "1946", "1947", "1948", "1949", "1950",
            "1951", "1952", "1953", "1954", "1955", "1956", "1957", "1958", "1959", "1960", "1961",
            "1962", "1963", "1964", "1965", "1966", "1967", "1968", "1969", "1970", "1971", "1972",
            "1973", "1974", "1975", "1976", "1977", "1978", "1979", "1980", "1981", "1982", "1983",
            "1984", "1985", "1986", "1987", "1988", "1989", "1990", "1991", "1992", "1993", "1994",
            "1995", "1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003", "2004", "2005",
            "2006", "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016",
            "2017", "2018", "2019", "2020", "2021", "2022", "2023", "2024", "2025", "2026", "2027",
            "2028", "2029", "2030", "2031", "2032", "2033", "2034", "2035", "2036", "2037", "2038",
            "2039", "2040", "2041", "2041", "2043", "2044", "2045", "2046", "2047", "2048", "2049",
            "2050", "2051", "2052", "2053", "2054", "2055", "2056", "2057", "2058", "2059", "2060",
            "2061", "2062", "2063", "2064", "2065", "2066", "2067", "2068", "2069", "2070", "2071",
            "2072", "2073", "2074", "2075", "2076", "2077", "2078", "2079", "2080", "2081", "2082",
            "2083", "2084", "2085", "2086", "2087", "2088", "2089", "2090", "2091", "2091", "2093",
            "2094", "2095", "2096", "2097", "2098", "2099", "2100" };
    // 各年份對應之生肖
    public static final String sanSho[]         = { "牛", "虎", "兔", "龍", "蛇", "馬", "羊", "猴", "雞",
            "狗", "豬", "鼠", "牛", "虎", "兔", "龍", "蛇", "馬", "羊", "猴", "雞", "狗", "豬", "鼠", "牛", "虎",
            "兔", "龍", "蛇", "馬", "羊", "猴", "雞", "狗", "豬", "鼠", "牛", "虎", "兔", "龍", "蛇", "馬", "羊",
            "猴", "雞", "狗", "豬", "鼠", "牛", "虎", "兔", "龍", "蛇", "馬", "羊", "猴", "雞", "狗", "豬", "鼠",
            "牛", "虎", "兔", "龍", "蛇", "馬", "羊", "猴", "雞", "狗", "豬", "鼠", "牛", "虎", "兔", "龍", "蛇",
            "馬", "羊", "猴", "雞", "狗", "豬", "鼠", "牛", "虎", "兔", "龍", "蛇", "馬", "羊", "猴", "雞", "狗",
            "豬", "鼠", "牛", "虎", "兔", "龍", "蛇", "馬", "羊", "猴", "雞", "狗", "豬", "鼠", "牛", "虎", "兔",
            "龍", "蛇", "馬", "羊", "猴", "雞", "狗", "豬", "鼠", "牛", "虎", "兔", "龍", "蛇", "馬", "羊", "猴",
            "雞", "狗", "豬", "鼠", "牛", "虎", "兔", "龍", "蛇", "馬", "羊", "猴", "雞", "狗", "豬", "鼠", "牛",
            "虎", "兔", "龍", "蛇", "馬", "羊", "猴", "雞", "狗", "豬", "鼠", "牛", "虎", "兔", "龍", "蛇", "馬",
            "羊", "猴", "雞", "狗", "豬", "鼠", "牛", "虎", "兔", "龍", "蛇", "馬", "羊", "猴", "雞", "狗", "豬",
            "鼠", "牛", "虎", "兔", "龍", "蛇", "馬", "羊", "猴", "雞", "狗", "豬", "鼠", "牛", "虎", "兔", "龍",
            "蛇", "馬", "羊", "猴",                };

    /**
     * description:把轉換date的格式按原先格式format1轉成format2
     * 
     * @param date
     * @param format1
     * @param format2
     * @return
     */
    public static String convertDate(String date, String format1, String format2) {
        if ("".equals(date) || "00000000".equals(date)) {
            return "";
        }
        SimpleDateFormat fmt1 = new SimpleDateFormat(format1);
        SimpleDateFormat fmt2 = new SimpleDateFormat(format2);
        String rtnStr = null;
        try {
            Date d = fmt1.parse(date);
            rtnStr = fmt2.format(d);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rtnStr;
    }

    /**
     * 轉換主機日期(MM/dd/yyyy)為yyyy/MM/dd格式 <br/>
     * 
     * @param hostDate
     * @return
     */
    public static String convertMMDDYYYYWithSlashToYYYYMMDDWithSlash(String hostDate) {

        SimpleDateFormat fmt1 = new SimpleDateFormat("MM/dd/yyyy");
        SimpleDateFormat fmt2 = new SimpleDateFormat("yyyy/MM/dd");
        String rtnStr = "";

        if (hostDate == null) {
            return "";
        } else if (hostDate.trim().equals("")) {
            return "";
        }

        if (hostDate.equals("00/00/0000")) {
            rtnStr = "0000/00/00";
        } else {
            Date date;
            try {
                date = fmt1.parse(hostDate);
                rtnStr = fmt2.format(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        return rtnStr;
    }

    /**
     * 把DB的datetime類型的日期轉換成畫面顯示的日期。 DB的日期類型為yyyy-MM-dd hh:mm:ss.sss
     * 轉換後的日期為yyyy/MM/dd
     * 
     * @param date
     * @return
     */
    public static String converDBDate2Dsp(String date) {
        return DateUtil.convertDate(date, Constants.DATE_YYYYMMDDHHSSMMSSS_DOT,
            Constants.DATE_YYYYMMDD_SEPARATE);
    }

    /**
     * 把DB的datetime類型的日期轉換成畫面顯示的日期。 DB的日期類型為yyyy-MM-dd hh:mm:ss.sss
     * 轉換後的日期為yyyy/MM/dd hh:mm:ss author huotongwang
     * 
     * @param date
     * @return
     */
    public static String converDBDate2Dsp2(String date) {
        return DateUtil.convertDate(date, Constants.DATE_YYYYMMDDHHSSMMSSS_DOT,
            Constants.DATE_YYYYMMDDHHMMSS);
    }

    /**
     * description:把日期類型date按format的格式轉換成String類型
     * 
     * @param date
     * @param format
     * @return
     */
    public static String convertDate2String(Date date, String format) {
        SimpleDateFormat fmt = new SimpleDateFormat(format);
        String rtnStr = null;
        try {
            rtnStr = fmt.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rtnStr;
    }

    /**
     * description:把String日期date按format的格式轉換成Date類型
     * 
     * @param date
     * @param format
     * @return
     */
    public static Date convertString2Date(String date, String format) {
        SimpleDateFormat fmt = new SimpleDateFormat(format);
        Date rtnDate = null;
        try {
            rtnDate = fmt.parse(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rtnDate;
    }

    /**
     * description：計算兩個時間差，date2-date1
     * 
     * @param date1
     * @param date2
     * @return 時間相差秒數
     */
    public static long calcTimeSubtraction(Date date1, Date date2) {
        long diff = date2.getTime() - date1.getTime();
        long second = diff / (1000);
        return second;
    }

    /**
     * 依指定的格式回傳今天的日期<br/>
     * 
     * @param format
     *            "MM/dd/yyyy" "yyyy/MM/dd" "yyyy-MM-dd"
     * @return String
     */
    public static String getToday(String format) {

        Calendar cInstance = (Calendar) GregorianCalendar.getInstance().clone();
        Date date = new Date(cInstance.getTimeInMillis());
        SimpleDateFormat fmt = null;

        if (!format.equals("")) {
            fmt = new SimpleDateFormat(format);
        } else {
            fmt = new SimpleDateFormat();
        }

        return fmt.format(date);
    }

    /**
     * 回傳現在的日期時間,格式為YYYY/MM/DD hh:mm:ss <br/>
     * 
     * @return
     */
    public static String getNow() {

        return getNow("yyyy/MM/dd hh:mm:ss");
    }

    public static String getNow24() {

        return getNow("yyyy/MM/dd HH:mm:ss");
    }

    /**
     * 依指定格式回傳現在的日期時間,如指定格式為YYYY/MM/DD hh:mm:ss <br/>
     * 
     * @param format
     * @return
     */
    public static String getNow(String format) {
        Calendar cal = Calendar.getInstance();
        Date date = new Date(cal.getTimeInMillis());
        SimpleDateFormat fmt = new SimpleDateFormat(format);

        return fmt.format(date);
    }

    /**
     * 取得現在時間並以java.sql.Timestamp的方式回傳<br/>
     * 
     * @return
     */
    public static java.sql.Timestamp getNowInSqlTimestamp() {
        Calendar cal = Calendar.getInstance();
        Timestamp now = new Timestamp(cal.getTimeInMillis());

        return now;
    }

    /**
     * 取得現在時間的long值 <br/>
     * 
     * @return
     */
    public static long getNowToLong() {
        Calendar cal = Calendar.getInstance();
        return cal.getTimeInMillis();
    }

    /**
     * 按指定的格式返回當前時間
     * 
     * @param format
     * @return
     */
    public static String getCurrentDate(String format) {
        String rtnDate;
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        rtnDate = sdf.format(Calendar.getInstance().getTime());
        return rtnDate;
    }

    /**
     * 依指定格式回傳前一日的日期 <br/>
     * 
     * @param format
     * @return
     */
    public static String getYesterday(String format) {

        return getDateFromNow(-1, format);
    }

    /**
     * 依指定格式回傳距離現在幾天的日期<br/>
     * 
     * @param day
     *            (正整數:今天以後的天數;負整數則表往前幾天)
     * @param format
     *            "MM/dd/yyyy" "yyyy/MM/dd" "yyyy-MM-dd"
     * @return String
     */
    public static String getDateFromNow(int day, String format) {

        Calendar cal = Calendar.getInstance();
        DateFormat dateFormat = new SimpleDateFormat(format);
        cal.add(Calendar.DATE, day);

        return dateFormat.format(cal.getTime());
    }

    /**
     * 依指定格式回傳距離傳入日往前/往後幾天的日期 <br/>
     * 
     * @param fromDate
     * @param day
     * @param format
     * @return
     * @throws ParseException
     */
    public static String getDateFromOneDate(String fromDate, int day, String format)
                                                                                    throws ParseException {
        DateFormat dateFormat = new SimpleDateFormat(format);
        Date date = dateFormat.parse(fromDate);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, day);

        return dateFormat.format(cal.getTime());
    }

    /**
     * 依指定格式回傳距離傳入日往前/往後幾天的月份字串 <br/>
     * 
     * @param fromDate
     * @param day
     * @param format
     * @return
     * @throws ParseException
     */
    public static String getMonthFromOneDate(String fromDate, int day, String format)
                                                                                     throws ParseException {

        String targetDate = getDateFromOneDate(fromDate, day, format);
        if (targetDate == null) {
            throw new NumberFormatException();
        }

        if (targetDate.length() == 8) {
            return targetDate.substring(4, 6);
        }

        return null;
    }

    /**
     * 依指定格式回傳距離現在幾個月的日期
     * 
     * @param day
     * @param format
     * @return
     */
    public static String getMonthFromNow(int day, String format) {
        Calendar cal = Calendar.getInstance();
        DateFormat dateFormat = new SimpleDateFormat(format);
        cal.add(Calendar.MONTH, day);
        return dateFormat.format(cal.getTime());
    }

    /**
     * 將一long整數值轉為日期時間格式(YYYY/MM/DD hh:mm:ss) <br/>
     * 
     * @param value
     * @return
     */
    public static String convertLongToDateTime(long value) {

        Date date = new Date(value);
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");

        return fmt.format(date);
    }

    /**
     * 將指定的日期格式轉換為Long值回傳 <br/>
     * 格式必須為yyyy/MM/dd <br/>
     * 
     * @param date
     * @return
     * @throws ParseException
     */
    public static long convertDateToLong(String date) throws ParseException {

        return convertDateTimeToLong(date, "yyyy/MM/dd");
    }

    /**
     * 傳入一日期格式(yyyy/mm/dd)回傳當日的00:00:00之Long值 <br/>
     * 
     * @param date
     * @return
     * @throws ParseException
     */
    public static long convertDateBeginToLong(String date) throws ParseException {

        date = date + " 00:00:00";

        return convertDateTimeToLong(date, "yyyy/MM/dd hh:mm:ss");
    }

    /**
     * 傳入一日期格式(yyyy/mm/dd)回傳當日的23:59:59之Long值 <br/>
     * 
     * @param date
     * @return
     * @throws ParseException
     */
    public static long convertDateEndToLong(String date) throws ParseException {

        date = date + " 23:59:59";

        return convertDateTimeToLong(date, "yyyy/MM/dd hh:mm:ss");
    }

    /**
     * 將指定的日期格式轉換為Long值回傳 <br/>
     * 格式必須為yyyy/MM/dd hh:mm:ss<br/>
     * 
     * @param dateTime
     * @return
     * @throws ParseException
     */
    public static long convertDateTimeToLong(String dateTime) throws ParseException {

        return convertDateTimeToLong(dateTime, "yyyy/MM/dd hh:mm:ss");
    }

    /**
     * 依指定的格式,將日期或日期字串轉換為Long值回傳 <br/>
     * 格式可為yyyy/MM/dd 或yyyy/MM/dd hh:mm:ss ... <br/>
     * 
     * @param dateTime
     * @param fmtStr
     * @return
     * @throws ParseException
     */
    public static long convertDateTimeToLong(String dateTime, String fmtStr) throws ParseException {

        SimpleDateFormat fmt = new SimpleDateFormat(fmtStr);

        Date d = fmt.parse(dateTime);

        Calendar cal = Calendar.getInstance();

        cal.setTime(d);

        return cal.getTimeInMillis();

    }

    /**
     * 將一long整數值轉為日期格式(YYYY/MM/DD) <br/>
     * 
     * @param value
     * @return
     */
    public static String convertLongToDate(long value) {

        Date date = new Date(value);
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd");

        return fmt.format(date);
    }

    /**
     * description:轉日期格式
     * 
     * @param date
     * @param fromFormat
     * @param toFormat
     * @return
     */
    public static String transFormat(String date, String fromFormat, String toFormat) {

        String rtnDate = "";
        try {
            SimpleDateFormat sdf1 = new SimpleDateFormat(fromFormat);
            SimpleDateFormat sdf2 = new SimpleDateFormat(toFormat);
            Date d = sdf1.parse(date);
            rtnDate = sdf2.format(d);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rtnDate;
    }

    /**
     * 轉換主機下檔的時間格式(轉為hh:mm:ss格式) <br/>
     * 
     * @param time
     * @return
     * @throws ParseException
     */
    public static String convertTime(String time) {

        SimpleDateFormat fromFmt = new SimpleDateFormat("hh.mm.ss");
        SimpleDateFormat toFmt = new SimpleDateFormat("hh:mm:ss");
        Date t = null;

        if (time == null || (time.length() != 8) || time.equals("00000000")) {
            return "00:00:00";
        } else if (DataUtil.isNubmer(time)) {
            time = time.substring(0, 6);
            fromFmt = new SimpleDateFormat("hhmmss");
            try {
                t = fromFmt.parse(time);
            } catch (ParseException e1) {
                e1.printStackTrace();
            }
        } else {
            try {
                t = fromFmt.parse(time);
            } catch (ParseException e) {
                if (time.indexOf(":") != 1) {
                    return time;
                }
            }
        }

        return toFmt.format(t);
    }

    // sample: from 010995 to 0095/09/01
    public static String Date_DDMMYYYYtoYYYY_MM_DD(String str) {
        String outdate = "";
        if (str == null) {
            return outdate;
        }
        str = str.trim();
        if (!str.trim().equals("") && !str.equals("00000000") && !str.equals("99999999")) {
            try {
                // Convert String to Date
                SimpleDateFormat infmt = new SimpleDateFormat(Constants.DATE_HTG_DDMMYYYY);
                Date date = infmt.parse(str);

                // Convert Date to Output format
                SimpleDateFormat outfmt = new SimpleDateFormat(Constants.DATE_YYYYMMDD_SEPARATE);
                outdate = outfmt.format(date);

            } catch (Exception e) {
                e.printStackTrace();
                outdate = "";
            }
        } else if (str.equals("99999999")) {
            outdate = "9999/99/99";
        } else {
            outdate = "";
        }
        return outdate;
    }

    // sample: from 19950601 to 1995/06/01
    public static String Date_YYYYMMDDtoYYYY_MM_DD(String str) {
        String outdate = "";
        if (str == null) {
            return outdate;
        }
        str = str.trim();
        if (!str.equals("") && !str.equals("00000000") && !str.equals("0")
            && !str.equals("99999999")) {
            try {
                // Convert String to Date
                SimpleDateFormat infmt = new SimpleDateFormat(Constants.DATE_YYYYMMDD);
                Date date = infmt.parse(str);

                // Convert Date to Output format
                SimpleDateFormat outfmt = new SimpleDateFormat(Constants.DATE_YYYYMMDD_SEPARATE);
                outdate = outfmt.format(date);

                if (str.equals("19110000")) {
                    outdate = "0000/00/00";
                }

            } catch (Exception e) {
                // IR_Re-eng_20070713 Rita Zhou e.printStackTrace();
                e.printStackTrace();
                outdate = "";
            }
        } else if (str.equals("99999999")) {
            outdate = "9999/99/99";
        } else {
            outdate = "";
        }

        return outdate;
    }

    /**
     * 傳入西元年, 回傳該年度之農曆一月一日之國曆日期 <br/>
     * 
     * @param yyyy
     * @return
     * @throws DataFormatException
     */
    public static String getNonLiYanDonDate(String yyyy) throws DataFormatException {

        for (int i = 0; i < dateYear.length; i++) {
            if (dateYear[i].equals(yyyy)) {
                return dateYanDanDate[i];
            }
        }
        log.info("找不到對應的年份資料:" + yyyy);

        // throw new DataFormatException("找不到對應的年份資料!");
        return "0000";
    }

    /**
     * 傳入一年份資料(農曆年), 回傳該年所對應之生肖 <br/>
     * 
     * @param yyyy
     * @return
     * @throws DataFormatException
     */
    public static String getSanSho(String yyyy) throws DataFormatException {

        for (int i = 0; i < dateYear.length; i++) {
            if (dateYear[i].equals(yyyy)) {
                return sanSho[i];
            }
        }

        // throw new DataFormatException("找不到生肖資料!");
        return "N/A";
    }

    /**
     * description:根據輸入的時間，有fromFormat格式，轉換成toFormat格式
     * 
     * @param srcTime
     * @param fromFormat
     * @param toFormat
     * @return
     */
    public static String timeToDsp(String srcTime, String fromFormat, String toFormat) {
        String rtn = "";
        try {
            SimpleDateFormat fmt1 = new SimpleDateFormat(fromFormat);
            SimpleDateFormat fmt2 = new SimpleDateFormat(toFormat);
            try {
                if (srcTime != null && !"".equals(srcTime)) {
                    Date d = fmt1.parse(srcTime);
                    rtn = fmt2.format(d);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rtn;
    }

    /**
     * 取得當前月份
     * 
     * @return
     */
    public static int getCurrentMonth() {
        Calendar c = Calendar.getInstance();
        return c.get(Calendar.MONTH) + 1;
    }

    /**
     * description:把yyyy-MM-ddTHH:mm:ss+08:00的格式转换成format型
     * 例：2010-06-16T12:34:56+08:00转换成2010/06/16，format输入yyyy/MM/dd即可
     * 
     * @param calendar
     *            格式为yyyy-MM-ddTHH:mm:ss+08:00
     * @param format
     *            需要转换的类型，例如：yyyy/MM/dd
     * @return
     */
    public static String converCalendar(String calendar, String format) {

        // 將yyyy-MM-ddTHH:mm:ss+08:00 轉變格式為yyyy-MM-dd HH:mm:ss.sss
        StringBuffer strbuffer = new StringBuffer();
        strbuffer.append(calendar.replace("T", " ").substring(0, 19)).append(".").append("000");
        String rtn = null;
        SimpleDateFormat fmt1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.sss");
        SimpleDateFormat fmt2 = new SimpleDateFormat(format);
        try {
            Date date = fmt1.parse(strbuffer.toString());
            rtn = fmt2.format(date);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return rtn;
    }

    /**
     * 取系統當前月的前一個月，并轉換成兩位的MM例：8月即08月
     * 
     * @return
     */
    public static String getMonth() {
        Calendar c = Calendar.getInstance();
        String strmonth = Integer.toString((c.get(Calendar.MONTH) + 1) - 1);
        if (strmonth.length() == 1) {
            strmonth = "0" + strmonth;
        }
        return strmonth;
    }

    /**
     * 取得系統日的前一個月份，格式為：yyyyMM
     * 
     * @return
     * @author yun.tang
     * @since 2010/09/02
     */
    public static String getPreMonth() {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        Calendar day = Calendar.getInstance();
        day.add(Calendar.MONTH, -1);
        return sdf.format(day.getTime());
    }

    /**
     * 依指定月數及格式, 回傳指定的日期 <br/>
     * 
     * @param monthCnt
     * @param format
     * @return
     */
    public static String getMonthByMonthCnt(int monthCnt, String format) {

        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Calendar day = Calendar.getInstance();
        day.add(Calendar.MONTH, monthCnt);

        return sdf.format(day.getTime());
    }

    /**
     * 取得系統日的當前月份，格式為：yyyyMM
     * 
     * @return
     * @author yun.tang
     * @since 2010/09/02
     */
    public static String getCurrMonth() {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        return sdf.format(new Date());
    }

    /**
     * 取得系統日的下個月份，格式為：yyyyMM
     * 
     * @return
     * @author yun.tang
     * @since 2010/09/02
     */
    public static String getNextMonth() {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        Calendar day = Calendar.getInstance();
        day.add(Calendar.MONTH, 1);
        return sdf.format(day.getTime());
    }

    /**
     * 取得指定月份的天數，返回整型值
     * 
     * @param strDate
     *            輸入日期，格式為：yyyyMM
     * @return
     * @author yun.tang
     * @since 2010/09/02
     */
    public static int getDayOfMonth(String strDate) {

        int day = 0;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
            Calendar calendar = new GregorianCalendar();
            Date date = sdf.parse(strDate);
            calendar.setTime(date);
            day = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return day;
    }

    // 返回這個月有多少天
    public static int getDaysofMonth(String yyyyMM) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, Integer.parseInt(yyyyMM.substring(0, 4)));
        c.set(Calendar.MONTH, Integer.parseInt(yyyyMM.substring(4, 6)) - 1);
        c.set(Calendar.DAY_OF_MONTH, 1);
        return c.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    // 判斷今天是否是周六或周日工作日
    public static boolean isWeekday(String yyyyMMdd) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, Integer.parseInt(yyyyMMdd.substring(0, 4)));
        c.set(Calendar.MONTH, Integer.parseInt(yyyyMMdd.substring(4, 6)) - 1);
        c.set(Calendar.DAY_OF_MONTH, Integer.parseInt(yyyyMMdd.substring(6, 8)));
        int d = c.get(Calendar.DAY_OF_WEEK);
        if (d == 1 || d == 7) {
            return true;
        } else {
            return false;
        }
    }

    // 獲取一年半前時間
    public static String queryByHalfPastYear() {
        Calendar ca = Calendar.getInstance();
        ca.setTime(new Date());
        Date currentDate = ca.getTime();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd");
        String month = "";
        if (Integer.parseInt(sf.format(currentDate).split("/")[1]) - 6 < 0) {
            month = String
                .valueOf(12 + (Integer.parseInt(sf.format(currentDate).split("/")[1]) - 6));
        } else {
            month = String.valueOf(Integer.parseInt(sf.format(currentDate).split("/")[1]) - 6);
        }
        if (month.length() == 1) {
            month = "0" + month;
        }
        String halfonepastyear = (Integer.parseInt(sf.format(currentDate).split("/")[0]) - 1) + "/"
                                 + month + "/" + sf.format(currentDate).split("/")[2];
        return halfonepastyear;
    }

    public static String getCalendar2String(Calendar c) {
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        String sYear = String.valueOf(year);
        String sMonth = String.valueOf(month + 1);
        String sDay = String.valueOf(day);
        if (sMonth.length() == 1) {
            sMonth = "0" + sMonth;
        }
        if (sDay.length() == 1) {
            sDay = "0" + sDay;
        }
        return sYear + "-" + sMonth + "-" + sDay;
    }

    // 判斷今天是否是周六或周日工作日
    public static boolean isWeekday(Calendar c) {
        int d = c.get(Calendar.DAY_OF_WEEK);
        if (d == 1 || d == 7) {
            return true;
        } else {
            return false;
        }
    }

    // 返回這個月的第一天是星期幾 1:日 2：一 3：二
    public static int getFirstofMonth(String yyyyMM) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, Integer.parseInt(yyyyMM.substring(0, 4)));
        c.set(Calendar.MONTH, Integer.parseInt(yyyyMM.substring(4, 6)) - 1);
        c.set(Calendar.DAY_OF_MONTH, 1);
        return c.get(Calendar.DAY_OF_WEEK);
    }

    /**
     * 得到當天日期 + i天的日期，返回指定的日期格式
     * 
     * @param iDays
     *            天數
     * @param format
     *            日期格式：yyyyMMdd、yyyy/MM/dd、yyyy-MM-dd等
     * @return 返回日期字符串
     * @author yun.tang
     * @since 2010/09/21
     */
    public static String getDateByAddDays(int iDays, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Calendar day = Calendar.getInstance();
        day.add(Calendar.DATE, iDays);
        return sdf.format(day.getTime());
    }

    /**
     * 得到當天日期 + i月的日期，返回指定的日期格式
     * 
     * @param iMonths
     *            月數
     * @param format
     *            日期格式：yyyyMMdd、yyyy/MM/dd、yyyy-MM-dd等
     * @return 返回日期字符串
     * @author yun.tang
     * @since 2010/09/21
     */
    public static String getDateByAddMonths(int iMonths, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Calendar day = Calendar.getInstance();
        day.add(Calendar.MONTH, iMonths);
        return sdf.format(day.getTime());
    }

    /**
     * 得到當天日期 - i月的日期，返回指定的日期格式
     * 
     * @param iMonths
     *            月數
     * @param format
     *            日期格式：yyyyMMdd、yyyy/MM/dd、yyyy-MM-dd等
     * @return 返回日期字符串
     * @author Boyang.Long
     * @since 2010/12/31
     */
    public static String getDateByMinMonths(int iMonths, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Calendar day = Calendar.getInstance();
        day.add(Calendar.MONTH, iMonths);
        return sdf.format(day.getTime());
    }

    /**
     * 得到當天日期30天前的日期，返回指定的日期格式
     * 
     * @param iDays
     *            天數
     * @param format
     *            日期格式：yyyyMMdd、yyyy/MM/dd、yyyy-MM-dd等
     * @return 返回日期字符串
     * @author Boyang.Long
     * @since 2011/01/28
     */
    public static String getThirtyDaysBefore(int iDays, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Calendar day = Calendar.getInstance();
        day.add(Calendar.DAY_OF_YEAR, iDays);
        return sdf.format(day.getTime());
    }

    /**
     * 得到近一個月的日期,返回指定的日期格式
     */
    public static String[] getNearByMonth(int iMonths, String format) {
        String[] dateInfo = new String[2];
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Calendar day = Calendar.getInstance();
        // 前一個月
        day.add(Calendar.MONTH, -1);
        dateInfo[0] = sdf.format(day.getTime());
        // 系統年月
        Calendar day1 = Calendar.getInstance();
        dateInfo[1] = sdf.format(day1.getTime());
        return dateInfo;
    }

    /**
     * sample: from 110510 to 20101105
     * 
     * @param date
     * @return
     */
    public static String covertMMDDYYtoYYYYMMDD(String date) {
        if (StringUtil.isNull(date)) {
            return "";
        }
        String yy = date.substring(4);
        String mmdd = date.substring(0, 4);
        return "20" + yy + mmdd;
    }

    /**
     * sample: from 11052010 to 20101105
     * 
     * @param date
     * @return
     */
    public static String covertMMDDYYYYtoYYYYMMDD(String date) {
        if (StringUtil.isNull(date)) {
            return "";
        }
        String yyyy = date.substring(4);
        String mmdd = date.substring(0, 4);
        return yyyy + mmdd;
    }

    /**
     * 返回前/後幾分鐘，前輸入負數。例如，前5分鐘，輸入-5
     * 
     * @param date
     * @return
     */
    public static String getLastMinute(String date, int n) {
        Calendar c = Calendar.getInstance();
        c.setTime(DateUtil.convertString2Date(date, Constants.DATE_YYYYMMDDHHSSMMSSS_DOT));
        c.add(Calendar.MINUTE, n);
        c.getTime();
        return DateUtil.convertDate2String(c.getTime(), Constants.DATE_YYYYMMDDHHSSMMSSS_DOT);
    }

    /**
     * 測試用的main method <br/>
     * 
     * @param args
     * @throws ParseException
     */

    /**
     * 計算1天中2個時段的時間差 start: HH:mm end: HH:mm
     * 
     * @throws ParseException
     */
    public static String timeIsMoney(String start, String end) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");
        start = start.substring(0, 2) + ":" + start.substring(2, 4);
        end = end.substring(0, 2) + ":" + end.substring(2, 4);
        Date startDate = df.parse(start);
        Date endDate = df.parse(end);
        long l = endDate.getTime() - startDate.getTime();
        long day = 0;
        long hour = 0;
        double min = 0.0;
        if (l < 0) {
            day = l / (24 * 60 * 60 * 1000);
            hour = (l / (60 * 60 * 1000) - day * 24);
            min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
            if (min != 0) {
                hour = 23 + hour;
                min = 60 + min;
            } else {
                hour = 24 + hour;
            }
        } else {
            day = l / (24 * 60 * 60 * 1000);
            hour = (l / (60 * 60 * 1000) - day * 24);
            min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
        }
        // 計算計價單位數
        // if(min/60 == 0.5){
        // disTime = String.valueOf(hour + 0.5);
        // }else{
        // disTime = String.valueOf(hour);
        // }
        return hour + ":" + min;
    }

    /**
     * 根據一段時間后計算出結果時間
     */
    public static String sum1And2(String start, BigDecimal btime) {
        String sHour = "";
        String sMin = "";
        int startHour = Integer.parseInt(start.substring(0, 2));
        int startMin = Integer.parseInt(start.substring(2, 4));
        int addTime = Integer.parseInt(String.valueOf(btime).split("[.]")[0]);
        if (addTime % 60 == 0 && addTime != 0) {
            startHour = startHour + addTime / 60;
        } else {
            startHour = startHour + addTime / 60;
            startMin = startMin + addTime % 60;
            if (startMin % 60 == 0 && startMin != 0) {
                startHour++;
                startMin = 0;
            } else if (startMin > 60) {
                startHour = startHour + startMin / 60;
                startMin = startMin % 60;
            }
        }
        if (startHour > 24) {
            startHour = startHour % 24;
        }
        if (String.valueOf(startHour).length() == 1) {
            sHour = "0" + startHour;
        } else {
            sHour = String.valueOf(startHour);
        }
        if (String.valueOf(startMin).length() == 1) {
            sMin = "0" + startMin;
        } else {
            sMin = String.valueOf(startMin);
        }
        return sHour + sMin;
    }

    /**
     * 取得日期差 <br/>
     * 
     * @param strDate0
     * @param strDate1
     * @return 取得日期差之天數
     */
    public static long getDateDiff(String strDate0, String strDate1, String format) {
        long result = 0;
        try {
            Date date1 = new SimpleDateFormat(format).parse(strDate0);
            Date date2 = new SimpleDateFormat(format).parse(strDate1);
            result = (date1.getTime() - date2.getTime()) / (24 * 60 * 60 * 1000);
        } catch (ParseException e) {
            log.error("異動日期(" + strDate1 + ")日期格式錯誤：");
        }
        return result;
    }

    /**
     * 根據日期之差計算所在區域的所有日期
     * 
     * @param args
     * @throws ParseException
     */
    public static List<String> getAllDateByDistance(long distance, String format) {
        List<String> list = new ArrayList<String>();
        SimpleDateFormat smf = new SimpleDateFormat(format);
        for (int i = 0; i <= (int) distance; i++) {
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DAY_OF_YEAR, i);
            list.add(smf.format(cal.getTime()));
            // System.out.println(cal.getTime());
        }
        return list;
    }

    /**
     * 将传入的日期类型，根据Days参数，进行前后日期计算，传入的日期格式必须是：yyyy/MM/dd或yyyy-MM-dd
     * 
     * @param dateStr
     * @param iDays
     * @param format
     * @return
     */
    public static String getDateByAddDays(String dateStr, int iDays, String format) {
        if (dateStr.indexOf("-") == -1 && dateStr.indexOf("/") == -1) {
            return "";
        } else {
            Calendar c = Calendar.getInstance();
            c.set(Calendar.YEAR, Integer.parseInt(dateStr.substring(0, 4)));
            c.set(Calendar.MONTH, Integer.parseInt(dateStr.substring(5, 7)) - 1);
            c.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dateStr.substring(8, 10)));
            c.add(Calendar.DAY_OF_MONTH, iDays);
            return new SimpleDateFormat(format).format(c.getTime());
        }
    }

    /**
     * 獲取當前的時間 時間格式為:yyyy/MM/dd HH:mm 返回格式為:HH:mm
     */
    public static String getExactTime(String date) {
        SimpleDateFormat smf = new SimpleDateFormat(date);
        Calendar c = Calendar.getInstance();
        return smf.format(c.getTime()).split("[ ]")[1];
    }

    // 获取当月第一天
    public static String getFirstDayOfMonth(String format) {
        String str = "";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Calendar lastDate = Calendar.getInstance();
        lastDate.set(Calendar.DATE, 1);// 设为当前月的1号
        str = sdf.format(lastDate.getTime());
        return str;
    }

    // 计算当月最后一天,返回字符串
    public static String getLastDayOfMonth(String format) {
        String str = "";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Calendar lastDate = Calendar.getInstance();
        lastDate.set(Calendar.DATE, 1);// 设为当前月的1号
        lastDate.add(Calendar.MONTH, 1);// 加一个月，变为下月的1号
        lastDate.add(Calendar.DATE, -1);// 减去一天，变为当月最后一天
        str = sdf.format(lastDate.getTime());
        return str;
    }

    public static int search(int[] a, int x) {
        int start = 0, end = a.length - 1, mid = (start + end) / 2, temp;

        while (start <= end) {
            temp = a[mid];
            if (temp == x) {
                return mid + 1;
            }
            if (x < a[mid])
                end = mid - 1;
            if (x > a[mid])
                start = mid + 1;

            mid = (start + end) / 2;

        }

        return -10000000;

    }

    /**
     * 計算帳單年月的日期間隔例如：2001/01~2001/05返回：2001/01,2001/02,2001/03,2001/04,2001/05
     * 參數1：迄日(年) 參數2：迄日(月) 參數3：起日(年) 參數4：起日(月)
     */
    public static List<String> distance_BillsDate(String strEndYear, String strEndMonth,
                                                  String strStartYear, String strStartMonth) {
        List<String> list = new ArrayList<String>();
        int startMonth = 0;
        int startYear = 0;
        // 起始年月要小於等於迄今年月,否則跳出方法
        if (Integer.parseInt(strStartYear + strStartMonth) > Integer.parseInt(strEndYear
                                                                              + strEndMonth)) {
            System.out.println("起始年月不能大於迄今年月!");
            return new ArrayList<String>();
        }
        while (true) {
            if (startMonth == 13) {
                startMonth = 1;
                startYear = Integer.parseInt(strStartYear);
                startYear++;
                strStartMonth = String.valueOf(startMonth).length() == 1 ? "0" + startMonth
                    : "" + startMonth;
                strStartYear = String.valueOf(startYear);
            }
            if ((strStartYear + strStartMonth).equals(strEndYear + strEndMonth)) {
                list.add(strEndYear + strEndMonth);
                break;
            }
            list.add(strStartYear + strStartMonth);
            startMonth = Integer.parseInt(strStartMonth);
            startMonth++;
            strStartMonth = String.valueOf(startMonth).length() == 1 ? "0" + startMonth
                : "" + startMonth;
        }
        return list;
    }

    /**
     * 得到几天前的时间
     * 
     * @param date
     * @param day
     * @return
     */
    public static Date getDateBefore(Date date, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
        return now.getTime();
    }

    /**
     * 將太陽日轉為yyyyMMdd格式
     * 
     * @param yddd
     * @return
     */
    public static String convertYDDDToYYYYMMDD(String yddd) {
        if (yddd == null || yddd.equals("")) {
            return "";
        }
        int i = 0;
        int month1[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        int month2[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        int year = Integer.parseInt(DateUtil.getNow("yyyy").substring(0, 3) + yddd.substring(0, 1));
        int date = Integer.parseInt(yddd.substring(1));
        String strMonth = "";
        String strDate = "";
        if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
            for (i = 0; i < 12; i++) {
                if (date <= month1[i])
                    break;
                date = date - month1[i];
            }
        } else {
            for (i = 0; i < 12; i++) {
                if (date <= month2[i])
                    break;
                date = date - month2[i];
            }
        }
        strMonth = String.valueOf(i + 1);
        strDate = String.valueOf(date);
        if (strMonth.length() < 2) {
            strMonth = "0" + strMonth;
        }
        if (strDate.length() < 2) {
            strDate = "0" + strDate;
        }
        return year + strMonth + strDate;
    }

    public static void main(String args[]) throws ParseException, UnsupportedEncodingException {
        /*
         * List<String> list = distance_BillsDate("2003" , "01" , "2002" ,
         * "03"); for(int i = 0 ; i < list.size() ; i ++){
         * System.out.println(list.get(i)); } SimpleDateFormat sdf = new
         * SimpleDateFormat("yyyyMMdd");
         * System.out.println(sdf.format(getDateBefore(new Date(), 30)));
         */

        /*
         * String result = DateUtil.getMonthByMonthCnt(36, "MMyy");
         * System.out.println("result=" + result);
         */

        System.out.println(DateUtil.convertYDDDToYYYYMMDD("1261"));

        System.out.println(DateUtil.convertMMDDYYYYWithSlashToYYYYMMDDWithSlash("00/00/0000"));
        System.out.println(DateUtil.convertMMDDYYYYWithSlashToYYYYMMDDWithSlash("08/19/2010"));

    }
}
